package com.won.project.bridge.channel

import android.content.Context
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel

class AndroidPlatformPlugin : FlutterPlugin {

    //接收flutter平台方法渠道
    private var methodChannel: MethodChannel? = null

    //发送flutter平台事件渠道
    private var eventChannel: EventChannel? = null

    override fun onAttachedToEngine(binding: FlutterPluginBinding) {
        setupChannels(binding.binaryMessenger, binding.applicationContext)
    }

    override fun onDetachedFromEngine(binding: FlutterPluginBinding) {
        teardownChannels()
    }

    private fun setupChannels(messenger: BinaryMessenger, context: Context) {
        methodChannel = MethodChannel(messenger, PlatformConst.MethodChannel)
        eventChannel = EventChannel(messenger, PlatformConst.EventChannel)

        val methodCallHandler = AndroidMethodCallHandlerImpl()
        val eventStreamHandler = AndroidEventStreamHandlerImpl()

        methodChannel?.setMethodCallHandler(methodCallHandler)
        eventChannel?.setStreamHandler(eventStreamHandler)
    }

    private fun teardownChannels() {
        methodChannel?.setMethodCallHandler(null)
        eventChannel?.setStreamHandler(null)
        methodChannel = null
        eventChannel = null
    }

}